package cn.iocoder.yudao.module.mini.service.address;

import cn.iocoder.yudao.module.mini.dal.dataobject.address.MiniAddressDO;
import cn.iocoder.yudao.module.mini.dal.mysql.user.MiniUserMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.mini.controller.admin.address.vo.*;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.mini.convert.address.AddressConvert;
import cn.iocoder.yudao.module.mini.dal.mysql.address.MiniAddressMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mini.enums.ErrorCodeConstants.*;

/**
 * 用户地址 Service 实现类
 *
 * @author dzy
 */
@Service
@Validated
public class MiniAddressServiceImpl implements MiniAddressService {

    @Resource
    private MiniAddressMapper miniAddressMapper;

    @Resource
    private MiniUserMapper miniUserMapper;

    @Override
    public Long createAddress(AddressCreateReqVO createReqVO) {
        // 插入
        MiniAddressDO address = AddressConvert.INSTANCE.convert(createReqVO);
        miniAddressMapper.insert(address);
        // 返回
        return address.getId();
    }

    @Override
    public void updateAddress(AddressUpdateReqVO updateReqVO) {
        // 校验存在
        validateAddressExists(updateReqVO.getId());
        // 更新
        MiniAddressDO updateObj = AddressConvert.INSTANCE.convert(updateReqVO);
        miniAddressMapper.updateById(updateObj);
    }

    @Override
    public void deleteAddress(Long id) {
        // 校验存在
        validateAddressExists(id);
        // 删除
        miniAddressMapper.deleteById(id);
    }

    private void validateAddressExists(Long id) {
        if (miniAddressMapper.selectById(id) == null) {
            throw exception(ADDRESS_NOT_EXISTS);
        }
    }

    @Override
    public MiniAddressDO getAddress(Long id) {
        MiniAddressDO miniAddressDO = miniAddressMapper.selectById(id);
        miniAddressDO.setCustomerName(miniUserMapper.selectById(miniAddressDO.getCustomerId()).getNickname());
        return miniAddressDO;
    }

    @Override
    public List<MiniAddressDO> getAddressList(Collection<Long> ids) {
        return miniAddressMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<MiniAddressDO> getAddressPage(AddressPageReqVO pageReqVO) {
        PageResult<MiniAddressDO> miniAddressDOPageResult = miniAddressMapper.selectPage(pageReqVO);
        miniAddressDOPageResult.getList().forEach(item -> {
            item.setCustomerName(miniUserMapper.selectById(item.getCustomerId()).getNickname());
        });
        return miniAddressDOPageResult;
    }

    @Override
    public List<MiniAddressDO> getAddressList(AddressExportReqVO exportReqVO) {
        return miniAddressMapper.selectList(exportReqVO);
    }

}
